package com.base.core.security;

import com.base.core.common.utils.JwtUtils;
import com.base.core.security.filter.JwtAuthFilter;
import com.base.moduleUser.service.UserRedisService;
import com.base.moduleUser.service.UserService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import java.util.Arrays;
import java.util.Collections;

@Configuration
@EnableWebSecurity
public class SecurityConfig {


    private final JwtUtils jwtUtils;

    private final UserService userService;

    private final UserRedisService userRedisService;

    // 通过构造器注入依赖
    public SecurityConfig(JwtUtils jwtUtils, UserService userService, UserRedisService userRedisService) {
        this.jwtUtils = jwtUtils;
        this.userService = userService;
        this.userRedisService = userRedisService;
    }

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
                .csrf(csrf -> csrf.disable()) // 使用Lambda风格禁用CSRF
                .authorizeHttpRequests(auth -> auth  // 使用Lambda风格的authorizeHttpRequests
                        // 放行OPTIONS请求，因为跨域请求可能会先发送OPTIONS预检请求
                        .requestMatchers(HttpMethod.OPTIONS, "/**").permitAll()
                        // 放行这些URL，不需要认证
                        .requestMatchers(
                                "/virtual/user/login",
                                "/virtual/user/register",
                                "/virtual/user/checkUsernameExists",
                                "/virtual/user/getCaptcha",
                                "/virtual/user/resetPassword",
                                "/virtual/user/changePassword",
                                "/virtual/user/verifyCaptcha",
                                "/virtual/dict/**",
                                "/virtual/task/**",
                                "/virtual/upload/file",
                                "/virtual/**",
                                "/virtual/AI/publishCsdnBlog"
                        ).permitAll()
                        .anyRequest().authenticated() // 其他请求需要认证
                )
                // 添加JWT过滤器
                .addFilterBefore(new JwtAuthFilter(jwtUtils, userService, userRedisService),
                        UsernamePasswordAuthenticationFilter.class)
                // 启用CORS配置（使用默认的CorsConfigurationSource bean）
                .cors(Customizer.withDefaults()); // 使用Customizer.withDefaults()启用CORS

        return http.build();
    }

    // CORS配置
    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowedOrigins(Collections.singletonList("*"));// 允许所有来源（生产环境应限制）
        config.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS"));
        config.setAllowedHeaders(Arrays.asList("*"));
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);
        return source;
    }
}